package kr.saeildamil.androidstudy_second2930;

import kr.saeildamil.androidstudy_second.R;
import kr.saeildamil.androidstudy_second2930.Localservice.LocalBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class BoundServiceTest extends Activity implements OnClickListener{
	Localservice mService;
	boolean mBound;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch30_boundservicetest);
		findViewById(R.id.ch30_boundservice_call).setOnClickListener(this);
	}
	@Override
	protected void onResume() {
		Log.d("BoundServiceTest", "onResume");
		super.onStart();
		Intent intent=new Intent(this, Localservice.class);
		bindService(intent, mConn, Context.BIND_AUTO_CREATE);
	}
	
	@Override
	protected void onPause() {
		Log.d("BoundServiceTest", "onPause");
		super.onStop();
		if(mBound){
			unbindService(mConn);
		}
	}

	ServiceConnection mConn=new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			mBound=false;
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.d("BoundServiceTest", "onServiceConnected");
			LocalBinder binder=(LocalBinder) service;
			mService=binder.getLocalservice();
			mBound=true;
		}
	};
	
	@Override
	public void onClick(View v) {
		if(mBound){
			Toast.makeText(this, Integer.toString(mService.getRandomNumber()), 0).show();
		}else{
			Toast.makeText(this, "서브스와 연결되지 않았습니다.", 0).show();
		}
	}

}
